package com.caiyouxi.finance.service;

import com.caiyouxi.common.Constant;
import com.caiyouxi.common.service.BaseService;
import com.caiyouxi.common.util.Log;
import com.caiyouxi.finance.mapper.CouponBatchMapper;
import com.caiyouxi.finance.model.CouponBatch;
import com.caiyouxi.finance.model.CouponType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;


/**
 * 券批次信息
 * chensong
 */
@Service
public class CouponBatchService extends BaseService {
    
    @Autowired
    private CouponBatchMapper couponBatchMapper;
    @Autowired
    private CouponTypeService couponTypeService;

    public CouponBatch select_coupon_batch(Integer couponBatchId){
        String key = "coupon_batch_" + couponBatchId;
        CouponBatch cb = (CouponBatch) redisService.get(key);
        if(cb == null){
            cb = couponBatchMapper.select_coupon_batch(couponBatchId);
            redisService.set(key,cb);
        }
        return cb;
    }

    public void add_coupon_batch(CouponBatch couponBatch){
        couponBatchMapper.add_coupon_batch(couponBatch);
        Log.d("保存券批次信息结束");
    }

    public void update_coupon_batch(CouponBatch couponBatch){
        couponBatchMapper.update_coupon_batch(couponBatch);
    }

    public void delete_coupon_batch(CouponBatch couponBatch){
        couponBatchMapper.delete_coupon_batch(couponBatch);
    }
    
    /**
     * 券批次校验
     */
    @Transactional
    public boolean check_coupon_batch(CouponBatch couponBatch,String fund_type){
        //先判断券种类状态是否启用
        CouponType coupontype = couponTypeService.select_coupon_type(Integer.valueOf(couponBatch.getType()));
        if(coupontype == null){
            Log.d("券种类不存在");
            return false;
        }
        if(!couponTypeService.check_coupon_type(coupontype,fund_type)){
            //券种类未启用
            Log.d("券种类未启用");
            return false;
        }
        Date date = new Date();//当前时间
        if(!Constant.COUPONS_BTACH_STATUS_APPROVED.equals(couponBatch.getApprove_status())){
            //券批次的状态非可用
            Log.d("券批次不可用——未审核通过");
            return false;
        }
        if(date.after(couponBatch.getExpire_time())){
            //不在券批次的有效期内
            Log.d("券批次已失效");
            //已过期更新状态为失效取消CANCELED
            couponBatch.setApprove_status(Constant.COUPONS_BTACH_STATUS_CANCELED);//被撤销/取消的；
            couponBatchMapper.update_coupon_batch(couponBatch);
            return false;
        }
        if(date.before(couponBatch.getStart_time())){
            //不在券批次的有效期内
            Log.d("券批次未生效");
            return false;
        }        
        return true;
    }
}
